package cn.zd.demo1;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.media.browse.MediaBrowser;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;

import cn.zd.demo1.service.VideoPlayerService;

public class VideoActivity extends AppCompatActivity implements View.OnClickListener {
    String videoUrl = "https://media.w3.org/2010/05/sintel/trailer.mp4";
    private MediaBrowserCompat mediaBrowser;
    private MediaControllerCompat mediaController;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);
        findViewById(R.id.btn_1).setOnClickListener(this);
        findViewById(R.id.v_1).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_1 || v.getId() == R.id.v_1) {
           /* Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(Intent.createChooser(intent, "Select Video"), 1);*/
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("video/*");
            startActivityForResult(intent, 1);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                Uri selectedVideoUri = data.getData();
                Toast.makeText(this,"选中的视频地址是"+selectedVideoUri.toString(),Toast.LENGTH_SHORT).show();
               /*VideoView videoView = findViewById(R.id.v_1);
                videoView.setVideoURI(selectedVideoUri);
                videoView.start();*/
                mediaBrowser = new MediaBrowserCompat(this, new ComponentName(this, VideoPlayerService.class), new MediaBrowserCompat.ConnectionCallback() {
                    @Override
                    public void onConnected() {
                        mediaController = new MediaControllerCompat(getApplicationContext(), mediaBrowser.getSessionToken());
                        mediaController.getTransportControls().playFromUri(selectedVideoUri, null);
                    }
                }, null);
                mediaBrowser.connect();
            }
        }
    }
}